// src/store/auth.js
import { defineStore } from 'pinia';
import axios from 'axios';
import router from '@/router'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null, // 用于存储用户信息
  }),
  actions: {
    async login(userForm) {
      const response = await axios.post('http://localhost/user/login', userForm)
      if (response.data.code === 20000) {
        // debugger
        this.user = response.data.data; // 保存用户信息  
        // alert(JSON.stringify(this.user))
        localStorage.setItem('auth', 'true');
        

        if(response.data.data.role === 1){
          // 根据role判断为用户还是管理员
          router.push('/home');
        }else{
          router.push('/user');
        } 
      }else{
        alert(response.data.message)
        router.push('/login')
      }

    },

    
    // 退出登录
    logout() {
      this.user = null;
      localStorage.setItem('auth', 'false');
    }
  },
});